package controller

import (
	"admin/model"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// 获取
func AddStudent(ctx *gin.Context) {
	modelNew := &model.Student{}
	ctx.ShouldBind(modelNew)
	err := db.Create(modelNew).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "添加失败，请检查数据学号是否重复",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "添加成功",
	})
}

// 获取
func GetStudent(ctx *gin.Context) {
	var modelNews []model.Student
	search := ctx.Query("search")
	classesId := ctx.Query("classesId")
	number := ctx.Query("number")

	// 条件
	where := []string{}
	// 参数
	params := []interface{}{}

	// 搜索姓名
	if len(search) > 0 {
		where = append(where, "name like ?")
		params = append(params, "%"+search+"%")
	}

	// 搜索姓名
	if len(number) > 0 {
		where = append(where, "number like ?")
		params = append(params, "%"+number+"%")
	}

	// 班级
	if len(classesId) > 0 {
		cid, err := strconv.Atoi(classesId)
		if err == nil {
			where = append(where, "classes_id = ?")
			params = append(params, cid)
		}
	}

	if len(where) > 0 {
		db.Preload("Classes").Where(strings.Join(where, " and "), params...).Debug().Find(&modelNews)
	} else {
		db.Preload("Classes").Find(&modelNews)
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "获取成功",
		"data":    modelNews,
	})
}

// 删除
func DelStudent(ctx *gin.Context) {
	type DeleteField struct {
		Id int `json:"id"`
	}
	deleteField := DeleteField{}
	ctx.ShouldBind(&deleteField)
	err := db.Where("id = ?", deleteField.Id).Unscoped().Delete(new(model.Student)).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "删除失败",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "删除成功",
	})
}

// 更新
func PutStudent(ctx *gin.Context) {
	type DeleteField struct {
		Id   int           `json:"id"`
		Data model.Student `json:"data"`
	}
	deleteField := DeleteField{}
	ctx.ShouldBind(&deleteField)
	err := db.Where("id = ?", deleteField.Id).Debug().Updates(deleteField.Data).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "更新失败,确认此记录是否存在并且学号和姓名不能重复",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "更新成功",
	})
}
